package com.fis.mca;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import com.fis.mca.admin.AppClient;
import com.fis.mca.admin.AppUser;
import com.fss.dictionary.DefaultDictionary;
import com.vaadin.Application;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

import eu.livotov.tpt.TPTApplication;

public class MainApplication extends TPTApplication
{
//	public static MainApplication INSTANCE;
	private CustomLogin loginWindow;
	private MainWindow frmMain;
	private Window mainWindow;
	private String ipRemoteAddr;
	
	@Override
	public void applicationInit()
	{
		setTheme("mca");
		DefaultDictionary.setCurrentLanguage("EN");
		this.setLocale(new Locale("en","US"));
		mainWindow = new Window("FPT Payment System");
		setMainWindow(mainWindow);
//		INSTANCE = (MainApplication) mainWindow.getApplication();
		AppClient.reset(this);
		initMainWindow();
		initLoginWindow();
		reloadResource();
//		setMainWindow(new MainWindow());
	}

	@Override
	public void firstApplicationStartup()
	{
	}
	
	private void initMainWindow()
	{
		frmMain = new MainWindow();
	}
	
	private void initLoginWindow()
	{
		loginWindow = new CustomLogin(this);
	}
	
	public void reloadResource()
	{
		boolean login = (getUser() != null && getUser().isLoggedIn());
//		boolean login = AppClient.getLoginStatus();
		if (login)
		{
			mainWindow.setContent(frmMain);
//			frmMain.checkPermission();
//			frmMain.setUsernameCaption(getUser().getUserName());
			
			frmMain.initComponent();
			frmMain.setUsernameCaption(getUser().getUserName());
			frmMain.updateLanguage();
			((VerticalLayout)mainWindow.getContent()).removeStyleName("mca-login-background");
//			INSTANCE = (MainApplication) mainWindow.getApplication();
		}
		else
		{
			mainWindow.setContent(loginWindow);
			((VerticalLayout)mainWindow.getContent()).addStyleName("mca-login-background");
		}
		
//		frmMain.setVisible(login);
//		loginWindow.setVisible(!login);
		System.out.println("login checked");
	}
	
	public String getPermission(String moduleName)
	{
		return getUser().getPermission(moduleName);
	}

	@Override
	public AppUser getUser()
	{
		Object user = super.getUser();
		if (user instanceof AppUser)
		{
			return (AppUser) user;
		}
		
		return new AppUser();
	}
	
	@Override
	public void transactionStart(Application application, Object transactionData)
	{
		super.transactionStart(application, transactionData);
		if (getIpRemoteAddr() == null)
		{
			if (transactionData instanceof HttpServletRequest)
			{
				HttpServletRequest httpServletRequest = (HttpServletRequest) transactionData;
				setIpRemoteAddr(httpServletRequest.getRemoteAddr());
			}
		}
	}

	public String getIpRemoteAddr()
	{
		return ipRemoteAddr;
	}

	public void setIpRemoteAddr(String ipRemoteAddr)
	{
		this.ipRemoteAddr = ipRemoteAddr;
	}

}
